package com.pyip.reggie.controller;

import com.pyip.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

/**
 * 用于文件图片的上传及下载
 */
@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {
    @Value("${reggie.path}")
    private String basePath;
    /**
     * 用于文件上传
     * @param file
     * @return
     */
    @RequestMapping(value = "/upload",method = RequestMethod.POST)
    public R<String> uploadFile(MultipartFile file) throws IOException {
        log.info("文件上传");
        log.info(file.toString()); // 临时文件
        // 原始文件名
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf('.'));

        // 使用UUID创建文件名，防止文件名重复
        String fileName = UUID.randomUUID().toString() +suffix;
        // 查看根目录是否存在
        File dir = new File(basePath);
        if(!dir.exists()){
            dir.mkdirs();
        }
        // 将临时文件转存到指定位置
        // 有异常抛出，全局异常处理器处理
        file.transferTo(new File(basePath+fileName));


        return R.success(fileName);
    }

    @RequestMapping(value = "/download",method = RequestMethod.GET)
    public void downloadFile(String name, HttpServletResponse response) throws IOException {
        FileInputStream fileInputStream = new FileInputStream(new File(basePath + name));
        ServletOutputStream outputStream = response.getOutputStream();

        response.setContentType("image/jpeg");
        int len = 0;
        byte[] bytes = new byte[1024];
        while((len = fileInputStream.read(bytes)) != -1){
            outputStream.write(bytes,0,len);
            outputStream.flush();
        }
        // 关闭资源
        outputStream.close();
        fileInputStream.close();

    }
}
